package com.scut.fy.common.web.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.server.ServerWebExchange;

import javax.servlet.http.HttpServletRequest;

/**
 * TODO
 *
 * @author JY
 * @version 1.0
 * @date 2021/9/28
 */
public class UserAgentUtil {
    private static final Logger log = LoggerFactory.getLogger(UserAgentUtil.class);

    /**
     * 通过浏览器的user-agent识别设备的类型
     * 设备类型只分 PC 和 Phone
     * @param ServerWebExchange
     * @return
     */
    public static String getDeviceType(ServerWebExchange exchange) {

        final String userAgent = exchange.getRequest().getQueryParams().getFirst("User-Agent");
        return analysis(userAgent);
    }
    /**
     * 通过浏览器的user-agent识别设备的类型
     * 设备类型只分 PC 和 Phone
     * @param HttpServletRequest
     * @return
     */
    public static String getDeviceType(HttpServletRequest request) {

        final String userAgent = request.getHeader("User-Agent");
        return analysis(userAgent);
    }

    private static String analysis(String userAgent) {
        String deviceType = "PC";
        if (userAgent.contains("Windows")) {
            deviceType = "PC";
        }
        if (userAgent.contains("Linux")) {
            deviceType = "PC";
            if (userAgent.contains("Andriod")) {
                deviceType = "Phone";
            }
        }
        if (userAgent.contains("Mac OS")) {
            deviceType = "PC";
            if (userAgent.contains("iPad")) {
                deviceType = "Phone";
            }
            if (userAgent.contains("iPhone")) {
                deviceType = "Phone";
            }
        }
        else {
            log.error("查询不到User-Agent，识别不到设备类型，统一识别为PC");
        }
        return deviceType;
    }
}
